package com.ll.blog.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ll.blog.common.ApiResponse;
import com.ll.blog.contant.Constant;
import com.ll.blog.contant.ExceptionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;


public class AdminFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        Integer role = UserFilter.getRole();
        if (role == null){
            throw new RuntimeException();
        }
        if(Objects.equals(role, Constant.ROLE_USER)){
            HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
            servletResponse.setCharacterEncoding("UTF-8");
            PrintWriter writer = servletResponse.getWriter();
            writer.write(ApiResponse.error(ExceptionEnum.PERMISSION_DENIED).toString());
            writer.flush();
            writer.close();
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
